﻿using Aliyun.OSS;
using JX.Infrastructure.Common;
using JX.Infrastructure.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace JX.Infrastructure.AliyunOSS
{
	/// <summary>
	/// 阿里云OSS操作帮助类
	/// </summary>
	public class AliyunOssHelper
	{
		/// <summary>
		/// 上传本地文件到OSS。成功则通过ResultInfo.Data返回文件名，ResultInfo.Url返回完整的调用地址。
		/// </summary>
		/// <param name="localFilename">本地文件完整路径</param>
		/// <returns></returns>
		public static ResultInfo UploadToOSS(string localFilename)
		{
			ResultInfo resultInfo = new ResultInfo();
			var ossConfig = ConfigHelper.GetAppSettingSection<AliyunOssConfig>();
			if (!ossConfig.EnableOSS)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "未启用OSS功能";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(localFilename) || !File.Exists(localFilename))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "要上传的文件不存在";
				return resultInfo;
			}
			string fileExt = Path.GetExtension(localFilename).ToLower();
			string Prefix = Utility.GetFileTypeByExtension(fileExt);
			if(!string.IsNullOrEmpty(Prefix))
			{
				Prefix = Prefix + "/";
			}
			var objectName = Prefix + DataSecurity.MakeFileRndName() + fileExt;
			// 创建OSSClient实例。
			var client = new OssClient(ossConfig.Endpoint, ossConfig.AccessKeyId, ossConfig.AccessKeySecret);
			try
			{
				// 上传文件。
				var result = client.PutObject(ossConfig.BucketName, objectName, localFilename);
				resultInfo.Status = 1;
				resultInfo.Msg = "上传成功！";
				resultInfo.Url = ossConfig.BucketEndpoint + "/" + objectName;
				resultInfo.Data = objectName;
			}
			catch (Exception ex)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "上传失败！" + ex.Message;
				LogFactory.SaveDBLog("上传文件到OSS失败！", "本地文件：" + localFilename + "。异常信息：" + resultInfo.Msg,logCategory:LogCategory.Exception);
			}
			return resultInfo;
		}

		/// <summary>
		/// 通过指定前缀，得到所有对像列表
		/// </summary>
		/// <param name="prefix">要搜索的目录前缀</param>
		/// <returns></returns>
		public static List<string> GetListObject(string prefix = "")
		{
			var keys = new List<string>();
			var ossConfig = ConfigHelper.GetAppSettingSection<AliyunOssConfig>();
			if (!ossConfig.EnableOSS)
			{
				return keys;
			}
			// 创建OSSClient实例。
			var client = new OssClient(ossConfig.Endpoint, ossConfig.AccessKeyId, ossConfig.AccessKeySecret);
			try
			{
				ObjectListing result = null;
				string nextMarker = string.Empty;
				do
				{
					var listObjectsRequest = new ListObjectsRequest(ossConfig.BucketName)
					{
						Marker = nextMarker,
						MaxKeys = 100,
						Prefix = prefix
					};
					result = client.ListObjects(listObjectsRequest);
					foreach (var summary in result.ObjectSummaries)
					{
						keys.Add(ossConfig.BucketEndpoint + "/" + summary.Key);
					}
					nextMarker = result.NextMarker;
				} while (result.IsTruncated);
			}
			catch (Exception ex)
			{
				keys.Clear();
				LogFactory.SaveDBLog("得到OSS文件列表失败！", "前缀：" + prefix + "。异常信息：" + ex.Message, logCategory: LogCategory.Exception);
			}
			return keys;
		}
	}
}
